package com.wuseguang.springcloud.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wuseguang.springcloud.Classcardservice.ClassCardFieldService;
import com.wuseguang.springcloud.Classcardservice.ClassCardService;
import com.wuseguang.springcloud.JdbcTemplate.WXJdbc;
import com.wuseguang.springcloud.dao.jdbc.ClassNoticeJdbc;
import com.wuseguang.springcloud.dao.jdbc.ClassesJdbc;
import com.wuseguang.springcloud.dao.mapper.ClassNoticeMapper;
import com.wuseguang.springcloud.dao.repository.ClassNoticeRepository;
import com.wuseguang.springcloud.dao.repository.NoticeRepository;
import com.wuseguang.springcloud.dao.repository.StudentRepository;
import com.wuseguang.springcloud.entity.ClassNotice;
import com.wuseguang.springcloud.entity.Notice;
import com.wuseguang.springcloud.entity.Student;
import com.wuseguang.springcloud.service.ClassNoticeService;
import com.wuseguang.springcloud.util.*;
import com.wuseguang.springcloud.util.WeChat.TemplateTools;
import com.wuseguang.springcloud.util.WeChat.WXUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * <p>
 * 班级班牌通知表 服务实现类
 * </p>
 *
 * @author
 * @since 2020-01-15
 */
@Service
public class ClassNoticeServiceImpl implements ClassNoticeService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ClassNoticeMapper classNoticeMapper;
    @Autowired
    private ClassNoticeRepository classNoticeRepository;
    @Autowired
    private NoticeRepository noticeRepository;
    @Autowired
    private ClassNoticeJdbc classNoticeJdbc;
    @Autowired
    private ClassesJdbc classesJdbc;
    @Autowired
    private WXJdbc wXJdbc;
    @Autowired
    private ClassCardFieldService service;
    @Autowired
    private StudentRepository studentRepository;

    //推送接口
    @Autowired
    private ClassCardService classCardService;

    @Override
    public Result findClassNoticeList(String[] classId, String termId, String schoolId, Integer indexNo, Integer rows, String admin, String teacherId) {

        logger.info("查询班级的班牌通知 ClassNoticeServiceImpl - > findClassNoticeList");
        //查询的sql
        String sql = null;
        //查询的班级
        String classid = null;

        //判断班级为空并且等于管理
        if (classId.length == 0 && "0".equals(admin)) {
            //查询符合班级的班牌通知信息
            sql = "select n.id,n.content,n.url,n.state,n.publisher,t.head_portrait , DATE_FORMAT(n.opertime,'%Y-%m-%d') opertime,n.display `show`" +
                    ",n.pdisplay pshow,n.annex,n.website  from notice n  left join teacher t on (t.id=n.teacher_id)  where EXISTS " +
                    "(select * from class_notice cn where n.id =cn.notice_id )  and n.term_id =? and n.school_id =? ORDER BY n.id desc,n.opertime desc ";

        }
        //判断如果上传班级为空
        else if (classId.length == 0) {
            classid = classesJdbc.findClassIds(schoolId, teacherId);
            //查询符合班级的班牌通知信息
            sql = "select n.id,n.content,n.url,n.state,n.publisher,t.head_portrait , DATE_FORMAT(n.opertime,'%Y-%m-%d') opertime,n.display `show`,n.pdisplay pshow,n.annex,n.website   from notice n  left join teacher t on (t.id=n.teacher_id)  where EXISTS " +
                    "(select * from class_notice cn where n.id =cn.notice_id and  cn.class_id in (" + classid + ") )  and n.term_id =? and n.school_id =? ORDER BY n.id desc,n.opertime desc";

        } else {
            //转为String 类型
            classid = org.apache.commons.lang.StringUtils.join(classId, ",");
            //查询符合班级的班牌通知信息
            sql = "select n.id,n.content,n.url,n.state,n.publisher,t.head_portrait , DATE_FORMAT(n.opertime,'%Y-%m-%d') opertime,n.display `show`,n.pdisplay pshow ,n.annex,n.website   from notice n  left join teacher t on (t.id=n.teacher_id)  where EXISTS " +
                    "(select * from class_notice cn where n.id =cn.notice_id and  cn.class_id in (" + classid + ") )  and n.term_id =? and n.school_id =? ORDER BY n.id desc ,n.opertime desc";

        }


        //查询通知信息
        List<Map<String, Object>> list = classNoticeJdbc.queryListMap(sql, termId, schoolId);

        //查询通知的绑定班级信息
        sql = "select c.id,c.`name` from classes c WHERE EXISTS (select * from class_notice cn WHERE  c.id=cn.class_id and  cn.notice_id = ?)";
        //
        for (Map<String, Object> map : list) {

            List<Map<String, Object>> classList = classNoticeJdbc.queryListMap(sql, map.get("id"));
            map.put("list", classList);
        }

        //创建分页工具
        PagingTool tool = new PagingTool();
        //放入页码
        tool.setIndexNo(indexNo);
        //放入每页显示数量
        tool.setRows(rows);
        //放入角色集合
        tool.setList(list);
        //返回数据
        return new Result(new PaginationUtil<>(list.size(), rows, tool.getList(), indexNo));
    }

    @Override
    public Result addNotice(Integer show, Integer pshow, String[] classId, String content, String url, Integer state, String termId, String schoolId, String teacherId, String teacherName, String annex, String website) {

        logger.info("添加班级通知 ClassNoticeServiceImpl - > addNotice");

        Notice notice = new Notice();
        //发布人
        notice.setPublisher(teacherName);
        //数据来源（1pc端 ，2小程序）
        notice.setSource(1);
        //发布教师id
        notice.setTeacherId(Integer.valueOf(teacherId));
        //学期id
        notice.setTermId(Integer.valueOf(termId));
        //0不置顶，1置顶
        notice.setState(state);
        //图片url
        notice.setUrl(url);
        //内容
        notice.setContent(content);
        //0 不展示班牌 1展示班牌
        notice.setDisplay(1);
        //0 不展示小程序  1展示小程序
        notice.setPdisplay(pshow);
        //网址/网站
        notice.setWebsite(website);
        //附件
        notice.setAnnex(annex);

        //学校id
        notice.setSchoolId(Integer.valueOf(schoolId));

        notice.setOpertime(new Date());

        //添加同时获得通知id
        Integer noticeId = noticeRepository.save(notice).getId();

        //绑定班级的list
        List<ClassNotice> classNoticeList = new ArrayList<ClassNotice>();

        //循环添加
        for (int i = 0; i < classId.length; i++) {
            ClassNotice classNotice = new ClassNotice();
            //班级id
            classNotice.setClassId(Integer.valueOf(classId[i]));
            //通知id
            classNotice.setNoticeId(noticeId);
            classNotice.setSchoolId(Integer.valueOf(schoolId));
            classNoticeList.add(classNotice);
            service.classesAndCards(classId[i], "noticeflag", "1");
            /*if(pshow==1){
                officialAccountPush(teacherId,classId[i]);
            }*/
        }


        classNoticeRepository.saveAll(classNoticeList);
        logger.info("通知添加成功");
        //班牌后需操作

        return new Result();
    }

    @Override
    public Result deleteNotice(String id, String teacherId, String admin) {
        //修改心跳字段
        try {
            String sql1 = "SELECT class_id FROM class_notice WHERE `notice_id` = ?";
            List<Integer> integers = classesJdbc.queryListInteger(sql1, new Object[]{Integer.valueOf(id)});
            service.classesAndCards(integers, "noticeflag", "1");

            logger.info("删除班级通知");
            //根据id查询视频
            Notice notice = noticeRepository.findById(Integer.valueOf(id)).get();

            //判断如果是发布人删除全部
            if (teacherId.equals(notice.getTeacherId().toString()) || "0".equals(admin)) {
                logger.info("这里是发布人或者管理员");
                //删除班级视频数据
                noticeRepository.deleteById(Integer.valueOf(id));
                //删除所有绑定视频的班级
                String sql = "DELETE FROM class_notice WHERE `notice_id` = ? ";
                classNoticeJdbc.updateByParameter(sql, id);
                classCardService.classesAndCards(integers);
                //删除oss中的文件视频
                CallbackSample.deleteFile(notice.getUrl());
                return new Result();
            }

            //查询这个教室是不是年级组长
            List<String> groupLeader = classNoticeJdbc.findGradeLeader(teacherId);
            //判断集合大于0时进来
            if (groupLeader.size() > 0) {
                logger.info("年级组长");
                //删除这个视频的班级
                String sql = "DELETE FROM `class_notice` WHERE `class_id`  in (select id from classes where grade_id = ?)";
                //循环
                for (String gradeId : groupLeader) {
                    classNoticeJdbc.updateByParameter(sql, gradeId);
                }
                //再次查询这个视频是否还有班级
                sql = "select COUNT(1) count from class_notice where notice_id = ? ";
                //获取还有多少条
                int count = classNoticeJdbc.queryCount(sql, id);
                //判断如果没有班级绑定这个视频了就把这个视频删除掉
                if (count == 0) {
                    noticeRepository.deleteById(Integer.valueOf(id));
                    //删除oss中的文件视频
                    CallbackSample.deleteFile(notice.getUrl());
                }
                classCardService.classesAndCards(integers);
                return new Result();
            }
        } catch (Exception e) {

        }

        logger.info("无权限删除");
        return new Result(CodeUtil.NO_PUBLISHER_NO_CAO_ZU);
    }

    /**
     * 公众号推送
     * @param tacherId 教师id
     * @param classId 班级id
     */
    public void officialAccountPush(String  tacherId,String classId) {

       try{
           //获取token
           String accessToken = wXJdbc.getOfficialAccountAccessToken(0);
           //查询学生集合
           List<Student> sutList = studentRepository.findByClassId(Integer.valueOf(classId));
           //循环学生
           for(Student stu:sutList){
               //查询家长的小程序openId
               String sql = "select p.open_id_one,p.id,p.open_id_two  from parent p  LEFT JOIN parent_student ps on(ps.parent_id=p.id)where ps.student_id=?";

               //家长openid
               Map<String, Object> parent = wXJdbc.queryMap(sql, stu.getId());
               String openId = (String) parent.get("open_id_two");

               //判断openId是否为空
               if (!StringUtils.isEmpty(openId)) {
                   //班级id
                   sql = "select `name` string  from classes where id = ?";
                   String className = wXJdbc.queryString(sql, classId);

                   //教师名称
                   sql = "select `name` string from teacher where id = ?";
                   String tacherName = wXJdbc.queryString(sql, tacherId);

                   Map<String, Object> pushMap = new HashMap<>();
                   pushMap.put("first", "您好，亲爱的"+stu.getStudentName()+"家长");
                   pushMap.put("keyword1", className);
                   pushMap.put("keyword2", tacherName);
                   pushMap.put("keyword3", DateUtil.gettime());
                   pushMap.put("keyword4", "你有一条最新的班级通知信息，请查收。");
                   pushMap.put("remark", "感谢您的支持。");


                   //跳转小程序信息
                   JSONObject appletJson= new JSONObject();
                   //appletJson.put("appid","wx30b606bac7775eba");
                   //appletJson.put("pagepath","pages/evaluate/index");

                   //解析后的数据
                   JSONObject json = TemplateTools.initializationData(pushMap);
                   //推送公众号信息
                   WXUtil.officialAccountPush(accessToken, openId, "EMtidcCuWasdhCWg2Sspfi_r0hsppqyzjiG-baLXP4Q", "", appletJson, json);
               }
           }
       }catch (Exception e){
           logger.error("e",e);
       }

    }
}
